package com.ym.component;

import cn.dev33.satoken.stp.StpInterface;
import com.ym.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Cacheable(value = "permission", key = "'userId::' + #loginId",cacheManager = "redisCacheManager")
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return Optional.ofNullable(loginId)
                .map(i -> {
                    try {
                        String userId = String.valueOf(i);
                        return sysUserService.getPermissionNames(Integer.valueOf(userId));
                    } catch (NumberFormatException e) {
                        throw new RuntimeException("userId类型转换错误");
                    }
                })
                .orElseThrow(() -> new RuntimeException("userId不能为null"));
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Cacheable(value = "role", key = "'userId::' + #loginId",cacheManager = "redisCacheManager")
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return Optional.ofNullable(loginId)
                .map(i -> {
                    try {
                        String userId = String.valueOf(i);
                        return sysUserService.getRoleNames(Integer.valueOf(userId));
                    } catch (NumberFormatException e) {
                        throw new RuntimeException("userId类型转换错误");
                    }
                })
                .orElseThrow(() -> new RuntimeException("userId不能为null"));
    }
}

